package com.wanshu.common.result;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt封装 工具类
 * 安全认证 jwt token 生成与验证
 *
 * @author 张颖辉（zyh）
 * @version 1.0.0
 * @date 2023/06/10
 */
public class JWTUtils {

    private static String SECRET = "yh";

    public static String getToken(Map<String, String> payLoad) {
        // 声明头部信息
        HashMap<String, Object> header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");
        // 生成过期时间，当前时间 + xx秒
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 7); // 默认过期时间 7天
        // 设置 载荷 的数据
        JWTCreator.Builder builder = JWT.create();
        payLoad.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        return builder.withExpiresAt(calendar.getTime()).withHeader(header).sign(Algorithm.HMAC256(SECRET));
    }

    public static DecodedJWT verify(String token) {
        DecodedJWT verify = null;
        try {
            verify = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            //map.put("msg", "无效签名");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            // map.put("msg", "Token过期");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            // map.put("msg", "算法不一致");
        } catch (Exception e) {
            e.printStackTrace();
            // map.put("msg", "Token无效");
        }
        return verify;
    }
}
